﻿using DevComponents.DotNetBar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UniRlv.COL;
using UniRlv.Utility;
using UniRlv.Utility.Extend;

namespace UniRlv.UI.Main
{
    public partial class FrmLogin : OfficeForm
    {
        public FrmLogin()
        {
            InitializeComponent();
            this.EnableGlass = false;
        }

        private void FrmLogin_Load(object sender, EventArgs e)
        {
            txtUser.Text = ConfigurationHelper.AppGetString("loginName");

            //启动服务器
            //System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo();
            //Info.FileName = "UniRlv.Server.exe";//"calc.exe"为计算器，"notepad.exe"为记事本
            //System.Diagnostics.Process Proc = System.Diagnostics.Process.Start(Info);
            RestClient.GetInstance().EndPoint = "http://106.12.167.10:56200/Connortao/";

            //数据库连接字符串自动添加
            ConfigurationHelper.AddConnStringSet("connString", "server=.\\SQLEXPRESS08;database=UniRlv;uid=sa;pwd=connortao", "System.Data.SqlClient");
            bool b = ConfigurationHelper.AppGetBoolean("bAutoUpdate");

            if (b)
            {
                backgroundWorker1.RunWorkerAsync();
            }
            
        }

        private void btnQuit_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            Close();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (txtUser.Text.Trim().Length == 0)
            {
                MessageBox.Show("用户名不能为空！");
                txtUser.Focus();
                return;
            }

            if (txtPwd.Text.Trim().Length == 0)
            {
                MessageBox.Show("密码不能为空！");
                txtPwd.Focus();
                return;
            }


            string sql = EntityHelper.GetQuerySql<User>();
            string msg = string.Empty;

            if (!WorkSpace.GetInstance().Init(ConfigurationHelper.AppGetString("serverIP"), ref msg))
            {
                if (msg.Contains("Seagull"))
                {//bartender未安装，继续运行
                    MessageBox.Show("初始化工作空间失败：" + msg);
                }
                else
                {
                    MessageBox.Show("初始化工作空间失败：" + msg);
                    return;
                }
                
            }

            sql += string.Format(" where loginName='{0}' and password='{1}'", txtUser.Text, txtPwd.Text);
            User u = DALOpr.QuerySingle<User>(sql, ref msg);

            if (u==null)
            {
                MessageBox.Show("用户不存在或者密码不正确！");
            }
            else
            {
                PublicObject.CurUser = u;
                PublicObject.CurCompany = DALOpr.QuerySingle<CompanyInfo>(ref msg);

                ConfigurationHelper.AppSet("loginName", txtUser.Text);
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                Close();
            }

            AppHelper.Init();
        }

        private void FrmLogin_Activated(object sender, EventArgs e)
        {
            txtPwd.Focus();
            txtPwd.SelectAll();
        }

        private void txtUser_KeyDown(object sender, KeyEventArgs e)
        {
            if (txtUser.Focused && e.KeyCode == Keys.Enter)
            {
                txtPwd.Focus();
                txtPwd.SelectAll();
            }
        }

        private void txtPwd_KeyDown(object sender, KeyEventArgs e)
        {
            if (txtPwd.Focused && e.KeyCode == Keys.Enter)
            {
                btnLogin.PerformClick();
            }
        }

        private void btnTestConn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string msg = string.Empty;

            this.Cursor = Cursors.WaitCursor;

            if (!WorkSpace.GetInstance().Init(ConfigurationHelper.AppGetString("serverIP"), ref msg))
            {
                if (msg.Contains("Seagull"))
                {//bartender未安装，继续运行
                    MessageBox.Show("初始化工作空间失败：" + msg);
                }
                else
                {
                    this.Cursor = Cursors.Default;

                    MessageBox.Show("初始化工作空间失败：" + msg);
                    return;
                }

            }

            this.Cursor = Cursors.Default;

            if (DALOpr.TestConnect(ref msg))
            {
                
                MessageBox.Show("连接成功！");
            }
            else
            {
                MessageBox.Show("连接失败：" + msg);
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string[] localFiles = Directory.GetFiles(Application.StartupPath, "*.*", SearchOption.TopDirectoryOnly);
            string msg = string.Empty;
            List<FileParameter> toUpdate = null;

            if (localFiles != null && localFiles.Length > 0)
            {
                List<FileParameter> lps = new List<FileParameter>();
                foreach (var item in localFiles)
                {
                    FileInfo fi = new FileInfo(item);
                    FileParameter fp = new FileParameter();
                    FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(item);
                    fp.FileName = fi.Name;
                    fp.FolderPath = "UniRlv";
                    fp.FileSize = fi.Length;
                    fp.FileVer = fvi.ProductVersion;
                    fp.LastModifyTime = fi.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");

                    lps.Add(fp);
                }

                try
                {

                    RestClient.GetInstance().Method = EnumHttpVerb.POST;
                    RestClient.GetInstance().PostData = JsonHelper.ToJson(lps);
                    string resultPost = RestClient.GetInstance().HttpRequest("UniUpdateAPI/IfNeedUpdate");

                    if (!string.IsNullOrEmpty(resultPost))
                    {
                        toUpdate = JsonHelper.FromJson<List<FileParameter>>(resultPost);
                    }
                }
                catch (Exception exp)
                {
                    e.Result = exp.Message;
                    return;
                }
            }

            if (toUpdate != null && toUpdate.Count > 0)
            {
                e.Result = 2;
            }
            else
            {
                e.Result = 1;
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            int res = 0;

            if (int.TryParse(e.Result.ToString(), out res))
            {

                FileParameter fp;

                switch (res)
                {
                    case 0:
                        break;
                    case 1:
                        break;
                    case 2://有更新文件
                        if (MessageBox.Show("系统需要更新，是否立即升级？", "请确定", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
                        {
                            Application.ExitThread();

                            fp = new FileParameter();
                            fp.FileName = Application.ExecutablePath;
                            fp.FolderPath = "UniRlv";

                            Process p = new Process();
                            p.StartInfo.FileName = Path.Combine(Application.StartupPath, "Update.exe");
                            string json = JsonHelper.ToJson(fp);
                            p.StartInfo.Arguments = Convert.ToBase64String(Encoding.GetEncoding("GBK").GetBytes(json));
                            p.Start();
                        }

                        return;
                    default:
                        break;
                }
            }
            else
            {
                MessageBox.Show("检测升级失败：" + e.Result);
            }
        }
    }
}
